using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Board board;
    public Camera camera;
    public Transform worldPos;
    public Pattern pattern;

    public int weight;
    public int height;

    public int score;
    public TMP_Text scoreUI;

    public bool isGameOver;
    public Transform UIGameover;
    private void Awake()
    {
        Instance = this;

        board = FindObjectOfType<Board>();
        board.CreateBoard();

        camera = FindObjectOfType<Camera>();
        camera.transform.position = new Vector3(weight * 0.5f - 0.5f, height * 0.5f - 0.5f, -10);
        Camera.main.orthographicSize = weight;

        worldPos = GameObject.Find("WorldPos").GetComponent<Transform>();
        pattern = GameObject.Find("Pattern").GetComponent<Pattern>();
    }

    private void Start()
    {
        pattern.CreateNewPattern();
        score = 0;
    }

    public void RefreshUI()
    {
        scoreUI.text = "Score: " + score.ToString();
    }

    private float intervalTime = 1f;
    private float currentTime;

    private void Update()
    {
        if (isGameOver)
        {
            UIGameover.gameObject.SetActive(true);
            return;
        }
        
        currentTime -= Time.deltaTime;
        if (currentTime <= 0)
        {
            pattern.Falling();
            currentTime = intervalTime;
        }

        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            pattern.LeftOrRightMove(new Vector2(-1, 0));
        }

        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            pattern.LeftOrRightMove(new Vector2(1, 0));
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            pattern.RotationSelf();
        }

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            currentTime = 0;
        }
    }
}